import React, {useState, useEffect} from 'react';
import moment from "moment";
import {connect} from 'react-redux';
import Taro, {getCurrentInstance, useDidShow} from '@tarojs/taro';
import {View, Text, Image} from '@tarojs/components';
import {AtForm, AtInput, AtButton} from 'taro-ui';
import {Input, DatePicker, Picker} from '@nutui/nutui-react-taro';
import {ArrowDown2} from '@nutui/icons-react-taro';
import getBaseUrl from "../../../service/baseUrl";
import './index.less';
import LicensePlateKeyboard from '../../../components/LicensePlateKeyboard';
import defaultVehicleLicense from '../../../assets/license.png';


const base = getBaseUrl();

function AddCharge(props) {
  const {dispatch, preRecord = {}} = props;
  const params = getCurrentInstance()?.router?.params || {}; // 路由参数
  console.log('路由参数', params);
  const [carNum, setCarNum] = useState('');
  const [carPhoneNumber, setPhoneNumber] = useState('');
  const [vin, setVin] = useState('');
  const [showKeyboard, setShowKeyboard] = useState(false);
  const [vehicleInfo, setVehicleInfo] = useState({
    plateNumber: '',
    vin: '',
    model: '',
    registerDate: '',
    owner: '',
    address: '',
    engineNo: '',
    useCharacter: '',
  });
  const [licenseImage, setLicenseImage] = useState('');
  const defaultValue = new Date()
  const defaultDescription = `${defaultValue.getFullYear()}-${
    defaultValue.getMonth() + 1
  }-${defaultValue.getDate()}`;
  let currentDate = new Date();
  currentDate.setHours(currentDate.getHours() + 12);
// 提取年、月、日、时、分、秒
  let year = currentDate.getFullYear();
  let month = currentDate.getMonth(); // 注意：月份是从 0 开始的（0 表示 1 月）
  let day = currentDate.getDate();
  let hours = currentDate.getHours();
  let minutes = currentDate.getMinutes();
  let seconds = currentDate.getSeconds();
  const startDate = new Date()
  // const endDate = new Date(year, month, day, hours, minutes, seconds)
  const endDate = new Date(startDate.getTime() + 12 * 60 * 60 * 1000) //往后推12小时
  // const endDate = new Date(moment().add(12, "hours").get('years'), moment().add(12, "hours").get('month'), moment().add(12, "hours").get('days'));
  console.log('startDate', startDate);
  console.log('endDate', endDate);
  const [show, setShow] = useState(false)
  const [desc, setDesc] = useState('');
  const [desc2, setDesc2] = useState('');
  const [visible, setVisible] = useState(false)
  const [visible2, setVisible2] = useState(false)
  const [baseDesc, setBaseDesc] = useState('')
  const listData1 = [
    [
      {
        value: preRecord.id,
        text: preRecord.vehiclePlate,
        ...preRecord
      },
      // { value: 1, text: '南京市' },
      // { value: 2, text: '无锡市' },
      // { value: 3, text: '海北藏族自治区' },
      // { value: 4, text: '北京市' },
      // { value: 5, text: '连云港市' },
      // { value: 8, text: '大庆市' },
      // { value: 9, text: '绥化市' },
      // { value: 10, text: '潍坊市' },
      // { value: 12, text: '乌鲁木齐市' },
    ],
  ]
  const changePicker = (list, option, columnIndex) => {
    console.log(columnIndex, option)
  }
  useEffect(() => {
    dispatch({
      type:'order/getPreRecord'
    })
  }, [dispatch])
  const confirm = (values, options) => {
    console.error('values', values);
    console.error('options', options);
    setDesc(options.map((option) => option.text).join(''));
    setDesc2(values.slice(0, 3).join('-') + ' ' + values.slice(3).join(':'));
    console.log('values.slice(0, 2).join(\'-\') + \' \' + values.slice(3).join(\':\')', values.slice(0, 3).join('-') + ' ' + values.slice(3).join(':'));
  }
  const formatter = (type, option) => {
    switch (type) {
      case 'year':
        option.text += `年`
        break
      case 'month':
        option.text += `月`
        break
      case 'day':
        option.text += `日`
        break
      case 'hour':
        option.text += `时`
        break
      default:
        option.text += ''
    }
    return option
  }
  const confirmPicker = (
      options,
      values
  ) => {
    console.log('confirmPickeroptions', options);
    console.log('confirmPickervalues', values);
    // bookTel
    // bookVin
    // vehiclePlate
    setCarNum(options.length ? options[0].vehiclePlate : '');
    setVin(options.length ? options[0].bookVin : '');
    setPhoneNumber(options.length ? options[0].bookTel : '');
    // let description = ''
    // options.forEach((option) => {
    //   description += ` ${option.text}`
    // })
    // setbaseDefault(description)
  }
  // 上传并识别行驶证
  const handleUploadLicense = async () => {
    try {
      // 选择图片
      const res = await Taro.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });

      if (res.tempFilePaths && res.tempFilePaths[0]) {
        setLicenseImage(res.tempFilePaths[0]);

        // 显示加载提示
        Taro.showLoading({
          title: '识别中...'
        });

        // 构建FormData并上传
        try {
          const uploadRes = await Taro.uploadFile({
            // url: 'YOUR_API_ENDPOINT/recognize-license', // 替换为您的实际接口地址
            url: `${base}/ocr/vehicleLicenseOCR`, // 替换为您的实际接口地址
            filePath: res.tempFilePaths[0],
            name: 'file', // 服务端接收文件的字段名
            formData: {
              'type': 'driving_license',
              'timestamp': new Date().getTime()
            },
            header: {
              'Content-Type': 'multipart/form-data',
              // 如果需要认证token
              'Authorization': "Bearer " + Taro.getStorageSync('access_token')
            }
          });
          console.log('uploadRes', uploadRes);
          // 解析响应数据
          const result = JSON.parse(uploadRes.data);
          console.log('uploadResresult', result);
          if (result.code && result.code === 200) {
            const licenseInfo = result.data;
            if (licenseInfo.vin) {
              setVehicleInfo({
                plateNumber: licenseInfo.plate_num || '',
                vin: licenseInfo.vin || '',
                model: licenseInfo.model || '',
                vehicle_type: licenseInfo.vehicle_type || '',
                registerDate: licenseInfo.register_date || '',
                owner: licenseInfo.owner || '',
                address: licenseInfo.addr || '',
                engineNo: licenseInfo.engine_num || '',
                useCharacter: licenseInfo.use_character || ''
              });

              setCarNum(licenseInfo.plate_num || '');
              setVin(licenseInfo.vin || '');

              Taro.hideLoading();
              Taro.showToast({
                title: '识别成功',
                icon: 'success'
              });
            } else {
              throw new Error('您上传的不是行驶证,请重新上传');
            }
          } else {
            throw new Error(result.message || '识别失败');
          }
        } catch (uploadError) {
          console.error('识别失败:', uploadError);
          Taro.hideLoading();
          Taro.showToast({
            title: uploadError.message || '识别失败',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('选择图片失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '选择图片失败',
        icon: 'none'
      });
    }
  };

  return (
    <View className='addWrap' onClick={() => setShowKeyboard(false)}>
      <View className='formWrap'>
        {/* 行驶证上传区域 */}
        <View className='license-upload' onClick={handleUploadLicense}>
          <Image
            className='license-image'
            src={licenseImage || defaultVehicleLicense}
            mode='aspectFit'
          />
          <Text className='upload-tip'>
            {licenseImage ? '点击重新上传' : '点击上传行驶证'}
          </Text>
        </View>

        <AtForm
          onSubmit={() => {
            if (carNum && vin && carPhoneNumber && desc) {
              // console.log('momentDesc', moment(desc));
              // console.log('momentDesc2', moment(desc2));
              // console.log('momentDescForm', moment(desc).format('YYYY-MM-DD HH:mm:ss'));
              // console.log('momentDescForm2', moment(desc2).format('YYYY-MM-DD HH:mm:ss'));
              // console.log('momentDescFormDate2', moment(desc2));
              // console.log('momentDescFormDate', new Date(desc2));
              dispatch({
                type: 'order/addOrder',
                payload: {
                  ...vehicleInfo,
                  carNumber: carNum,
                  stationId: params?.stationId,
                  stationName: params?.stationName,
                  pileCode: params?.pileCode,
                  gunNum: params?.gunCode ? parseInt(params?.gunCode) : null,
                  bookTel: carPhoneNumber,
                  bookVin: vin,
                  vehiclePlate: carNum,
                  scheduledChargingTime: moment(desc2).add(8, 'hours'),
                }
              })
            } else {
              Taro.showToast({
                title: '请完善必填信息再提交',
                icon: 'none',
                duration: 1500
              })
            }
          }}
        >
          <View className='input-item' onClick={() => setVisible2(true)}>
            <Text className='label'>信息复用</Text>
            <View className={`value placeholder`} style={{alignItems: 'center'}}>
              非必选
              {/*<View style={{width: '100%', display: 'flex', justifyContent: 'end', alignItems: 'center'}}>*/}
              {/*  可选*/}
              {/*</View>*/}
            </View>
          </View>
          <View className='input-item' onClick={() => setShow(true)}>
            <Text className='label'>预约时间</Text>
            <View className={`value ${!desc && 'placeholder'}`}>
              <DatePicker
                title="时间选择"
                type="datetime"
                formatter={formatter}
                defaultValue={new Date(`${defaultDescription} ${desc}`)}
                startDate={startDate}
                endDate={endDate}
                visible={show}
                onClose={() => setShow(false)}
                onConfirm={(options, values) => confirm(values, options)}
              />
              {desc || '必填'}
            </View>
          </View>
          <View className='input-item' onClick={(e) => {
            e.stopPropagation();
            setShowKeyboard(true)
          }}>
            <Text className='label'>车牌号</Text>
            <Text className={`value ${!carNum && 'placeholder'}`}>
              {carNum || '必填'}
            </Text>
          </View>
          <View className='input-item'>
            <Text className='label'>VIN码</Text>
            <View className={`value ${!vin && 'placeholder'}`}>
              <Input
                placeholder='必填'
                value={vin}
                onChange={(e) => setVin(e)}
                style={{paddingRight: 0, textAlign: 'end', fontSize: '32rpx'}}
              />
            </View>
          </View>
          <View className='input-item'>
            <Text className='label'>手机号码</Text>
            <View className={`value ${!carPhoneNumber && 'placeholder'}`}>
              <Input
                placeholder='必填'
                value={carPhoneNumber}
                onChange={(e) => setPhoneNumber(e)}
                style={{paddingRight: 0, textAlign: 'end', fontSize: '32rpx'}}
              />
            </View>
          </View>
          {/*<AtInput*/}
          {/*    name='model'*/}
          {/*    title='品牌型号'*/}
          {/*    type='text'*/}
          {/*    disabled*/}
          {/*    value={vehicleInfo.model}*/}
          {/*    onChange={(val) => setVehicleInfo(prev => ({...prev, model: val}))}*/}
          {/*/>*/}
          <AtInput
            name='vehicle_type'
            title='车辆类型'
            type='text'
            disabled
            value={vehicleInfo.vehicle_type}
            onChange={(val) => setVehicleInfo(prev => ({...prev, vehicle_type: val}))}
          />
          <AtInput
            name='registerDate'
            title='注册日期'
            type='text'
            disabled
            value={vehicleInfo.registerDate}
            onChange={(val) => setVehicleInfo(prev => ({...prev, registerDate: val}))}
          />

          {/*<AtInput*/}
          {/*  name='owner'*/}
          {/*  title='所有人'*/}
          {/*  type='text'*/}
          {/*  disabled*/}
          {/*  value={vehicleInfo.owner}*/}
          {/*  onChange={(val) => setVehicleInfo(prev => ({...prev, owner: val}))}*/}
          {/*/>*/}

          <AtInput
            name='engineNo'
            title='发动机号'
            type='text'
            disabled
            value={vehicleInfo.engineNo}
            onChange={(val) => setVehicleInfo(prev => ({...prev, engineNo: val}))}
          />

          <AtButton formType='submit'>预约</AtButton>
        </AtForm>
      </View>
      {showKeyboard && (
        <LicensePlateKeyboard
          value={carNum}
          onChange={setCarNum}
          onClose={() => setShowKeyboard(false)}
        />
      )}
      <Picker
          title="请选择车辆"
          visible={visible2}
          options={listData1}
          onConfirm={(list, values) => confirmPicker(list, values)}
          onClose={() => setVisible2(false)}
          onChange={changePicker}
      />
    </View>
  )
}

export default connect(({order}) => {
  return {
    ...order
  }
})(AddCharge)
